<template>
  <div class="profile-container">
    <!-- 第一部分：个人信息 -->
    <div class="profile-header">
      <div class="avatar-section">
        <a-avatar 
          :size="120" 
          :src=" user.avatar" 
        />
        <div class="username">{{ user.username }}</div>
        <div class="user-email">{{ user.email }}</div>
        <a-button v-if="isSelf" type="primary" @click="showEditModal" class="edit-btn">编辑资料</a-button>
        <a-button v-if="!isSelf" type="primary" 
            @click="onFollowClick" 
            :disabled="userStats.following"
            class="edit-btn">{{followText}}</a-button>
      </div>

      <div class="stats-section">
        <div class="stat-item">
          <a-progress
            type="circle"
            :percent="problemCompletionRate"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068'
            }"
            :width="80"
          >
            <span class="progress-text">{{ problemCompletionRate.toFixed(2) }}%</span>
          </a-progress>
          <div class="stat-label">题目完成率</div>
        </div>
        
        <div class="stats-row">
          <div class="stat-item">
            <div class="stat-number">{{ userStats.blogs.likes }}</div>
            <div class="stat-label">博客获赞</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.friends.following }}</div>
            <div class="stat-label">关注</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ userStats.friends.followers || 0 }}</div>
            <div class="stat-label">粉丝</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 第二部分：内容展示区 -->
    <div class="profile-content">
      <a-menu 
        mode="horizontal" 
        v-model:selectedKeys="activeContentKey"
        class="content-menu"
        @click="handleMainMenuSelect"
      >
        <a-menu-item key="problems">题目记录</a-menu-item>
        <a-menu-item key="blogs">我的博客</a-menu-item>
        <a-menu-item key="friends">好友列表</a-menu-item>
      </a-menu>

      <div class="content-display">
        <!-- 题目内容 -->
        <div v-if="activeContentKey[0] === 'problems'">
          <a-tabs @change="(key) => handleTabChange(key, 'problems')">
            <a-tab-pane key="1" tab="已通过">
              <a-spin :spinning="loading">
                <problem-list :problems="solvedProblems" />
          <a-pagination
            v-model:current="pagination.problems.current"
            :pageSize="pagination.problems.pageSize"
            :total="pagination.problems.solvedTotal"
            :showTotal="total => `共 ${total} 条`"
            @change="(page) => handlePaginationChange(page, 'solved')"
            style="margin-top: 16px; text-align: center"
          />
              </a-spin>
            </a-tab-pane>
            <a-tab-pane v-if="isSelf" key="2" tab="尝试中">
              <a-spin :spinning="loading">
                <problem-list :problems="attemptedProblems" />
          <a-pagination
            v-model:current="pagination.problems.current"
            :pageSize="pagination.problems.pageSize"
            :total="pagination.problems.attemptingTotal"
            :showTotal="total => `共 ${total} 条`"
            @change="(page) => handlePaginationChange(page, 'attempting')"
            style="margin-top: 16px; text-align: center"
          />
              </a-spin>
            </a-tab-pane>
          </a-tabs>
        </div>

        <!-- 博客内容 -->
        <div v-if="activeContentKey[0] === 'blogs'">
          <a-tabs @change="(key) => handleTabChange(key, 'blogs')">
            <a-tab-pane key="1" tab="已发布">
                <a-spin :spinning="loading">
                <BlogList 
                    :blogs="publishedBlogs" 
                    @blog-click="onBlogClick" 
                    @delete-blog="handleDeleteBlog"
                    :active="user.email === userStore.userStats.email"
                />
              <a-pagination
                v-model:current="pagination.blogs.current"
                :pageSize="pagination.blogs.pageSize"
                :total="pagination.blogs.publishedTotal"
                @change="(page) => handlePaginationChange(page, 'published')"
                style="margin-top: 16px; text-align: center"
              /></a-spin>
            </a-tab-pane>
            <a-tab-pane v-if="isSelf" key="2" tab="草稿">
               <a-spin :spinning="loading">
              <BlogList 
                :blogs="draftBlogs" 
                @blog-click="onBlogClick" 
                @delete-blog="handleDeleteBlog"
                :active="user.email === userStore.userStats.email"
              />
              <a-pagination
                v-model:current="pagination.blogs.current"
                :pageSize="pagination.blogs.pageSize"
                :total="pagination.blogs.draftsTotal"
                @change="(page) => handlePaginationChange(page, 'drafts')"
                style="margin-top: 16px; text-align: center"
              /></a-spin>
            </a-tab-pane>
            <a-tab-pane v-if="isSelf" key="3" tab="点赞的">
               <a-spin :spinning="loading">
              <BlogList 
                :blogs="likedBlogs" 
                @blog-click="onBlogClick" 
                @delete-blog="handleDeleteBlog"
                :active="user.email === userStore.userStats.email"
                :isLiked="true"
              />
              <a-pagination
                v-model:current="pagination.blogs.current"
                :pageSize="pagination.blogs.pageSize"
                :total="pagination.blogs.likedTotal"
                @change="(page) => handlePaginationChange(page, 'liked')"
                style="margin-top: 16px; text-align: center"
              /></a-spin>
            </a-tab-pane>
          </a-tabs>
        </div>

        <!-- 好友内容 -->
        <div v-if="activeContentKey[0] === 'friends'">
          <a-tabs @change="(key) => handleTabChange(key, 'friends')">
            <a-tab-pane key="1" tab="我关注的">
              <friend-list-with-follow :friends="following" />
            </a-tab-pane>
            <a-tab-pane key="2" tab="关注我的">
              <friend-list-with-follow :friends="followers" />
            </a-tab-pane>
            <a-tab-pane v-if="isSelf" key="3" tab="互相关注">
              <friend-list-with-follow :friends="mutualFriends" />
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>
    </div>

    <!-- 编辑资料弹窗 -->
    <a-modal 
      :open="editModalVisible" 
      title="编辑资料"
      :footer="null"
      @cancel="editModalVisible = false"
    >
      <a-menu mode="vertical" @click="handleEditMenuClick">
        <a-menu-item key="avatar">修改头像</a-menu-item>
        <a-menu-item key="username">修改用户名</a-menu-item>
        <a-menu-item key="password">修改密码</a-menu-item>
      </a-menu>
    </a-modal>

    <!-- 修改用户名子页面 -->
    <a-modal 
      :open="usernameModalVisible" 
      title="修改用户名"
      :footer="null"
      @cancel="backToEditModal"
    >
      <a-form :model="usernameForm" layout="vertical">
        <a-form-item label="新用户名">
          <a-input v-model:value="usernameForm.newUsername" />
        </a-form-item>
        <a-form-item>
          <div class="form-actions">
            <a-button 
              type="primary" 
              @click="updateUsername"
              class="confirm-btn"
            >
              确认修改
            </a-button>
            <a-button 
              @click="backToEditModal"
              class="cancel-btn"
            >
              返回
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改头像子页面 -->
    <a-modal 
      :open="avatarModalVisible" 
      title="修改头像"
      :footer="null"
      @cancel="backToEditModal"
    >
      <div class="avatar-edit-container">
        <div class="avatar-wrapper">
          <a-avatar 
            :size="200" 
            :src="avatarPreview || user.avatar"
            @click="$refs.avatarInput.click()"
            style="cursor: pointer"
          />
        </div>
        <input 
          type="file" 
          ref="avatarInput"
          accept="image/*"
          style="display: none"
          @change="handleAvatarChange"
        >
        <div class="form-actions">
          <a-button 
            type="primary" 
            :disabled="!avatarPreview"
            @click="updateAvatar"
            class="confirm-btn"
          >
            确认更换
          </a-button>
          <a-button 
            @click="backToEditModal"
            class="cancel-btn"
          >
            返回
          </a-button>
        </div>
      </div>
    </a-modal>

    <!-- 修改密码子页面 -->
    <a-modal 
      :open="passwordModalVisible" 
      title="修改密码"
      :footer="null"
      @cancel="backToEditModal"
    >
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item v-if="!useEmailVerification" label="当前密码">
          <a-input-password v-model:value="passwordForm.currentPassword" />
        </a-form-item>
        <a-form-item v-else label="验证码">
          <a-input-search 
            v-model:value="emailForm.verificationCode"
            placeholder="请输入验证码"
            enter-button="获取验证码"
            @search="sendVerificationCode"
          />
        </a-form-item>
        <a-form-item label="新密码">
          <a-input-password v-model:value="passwordForm.newPassword" />
        </a-form-item>
        <a-form-item label="确认新密码">
          <a-input-password v-model:value="passwordForm.confirmPassword" />
        </a-form-item>
        <a-form-item>
          <div class="form-actions">
            <a-button 
              type="primary" 
              @click="useEmailVerification ? changePasswordByEmail() : changePassword()"
              class="confirm-btn"
            >
              确认修改
            </a-button>
            <a-button 
              @click="backToEditModal"
              class="cancel-btn"
            >
              返回
            </a-button>
          </div>
        </a-form-item>
      </a-form>
      <a @click="toggleVerificationMethod" style="float: right">
        {{ useEmailVerification ? '使用密码验证' : '忘记密码？通过邮箱验证码修改' }}
      </a>
    </a-modal>
  </div>
</template>

<script>
import { useUserStore } from '@/stores/user';
import { useProblemStore } from '@/stores/problem'
import { useBlogStore } from '@/stores/blog'
import ProblemList from '@/components/ProblemList.vue';
import BlogList from '@/components/BlogList.vue';
import FriendListWithFollow from '@/components/FriendListWithFollow.vue';
import { getFollowStatus, follow, unfollow } from '@/api/user'
import { message, Modal } from 'ant-design-vue'
import { useChatStore } from '@/stores/chat'


export default {
  name: 'ProfileView',
  components: {
    ProblemList,
    BlogList,
    FriendListWithFollow
  },
  data() {
    const userStore = useUserStore();
    const blogStore = useBlogStore();
    const problemStore = useProblemStore();
    const chatStore = useChatStore();
    return {
      userStore,
      blogStore,
      problemStore,
      chatStore,
      userStats: {
        problems: { 
            solved: 0, 
            total: 0 
        },
        blogs: { likes: 0 },
        friends: { following: 0, followers: 0 }
      },
      user: {
        username:  '',
        email:  '',
        avatar: ''
      },
      editModalVisible: false,
      usernameModalVisible: false,
      passwordModalVisible: false,
      avatarModalVisible: false,
      avatarPreview: null,
      avatarPreviewByte: null,
      useEmailVerification: false,
      isSelf: true,
      usernameForm: {
        newUsername: ''
      },
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      emailForm: {
        verificationCode: ''
      },
      solvedProblems: [],
      attemptedProblems: [],
      loading: false,
      error: null,
      publishedBlogs: [],
      draftBlogs: [],
      likedBlogs: [],
      following: [],
      followers: [],
      mutualFriends: [],
      activeContentKey: ['problems'],
      pagination: { 
        problems: {
          current: 1,
          pageSize: 10,
          solvedTotal: userStore.userStats.stats.problems.solved,
          attemptingTotal: userStore.userStats.stats.problems.attempting
        },
        blogs: {
          current: 1,
          pageSize: 10,
          publishedTotal: userStore.userStats.stats.blogs.published,
          draftsTotal: userStore.userStats.stats.blogs.drafts,
          likedTotal: userStore.userStats.stats.blogs.liked
        },
        friends: {
          current: 1,
          pageSize: 10,
          followingTotal: userStore.userStats.stats.friends.following,
          followersTotal: userStore.userStats.stats.friends.followers,
          mutualTotal: userStore.userStats.stats.friends.mutual,
        }
      },
      isFollowing: false,
      isFollowers: false,
      followLoading: false
    }
  },
  computed: {
    // 博客分页数据
    paginatedPublishedBlogs() {
      const start = (this.pagination.blogs.current - 1) * this.pagination.blogs.pageSize;
      const end = start + this.pagination.blogs.pageSize;
      return this.publishedBlogs.slice(start, end);
    },
    paginatedDraftBlogs() {
      const start = (this.pagination.blogs.current - 1) * this.pagination.blogs.pageSize;
      const end = start + this.pagination.blogs.pageSize;
      return this.draftBlogs.slice(start, end);
    },
    paginatedLikedBlogs() {
      const start = (this.pagination.blogs.current - 1) * this.pagination.blogs.pageSize;
      const end = start + this.pagination.blogs.pageSize;
      return this.likedBlogs.slice(start, end);
    },
    // 好友分页数据由FriendListWithFollow组件内部处理
    problemCompletionRate() {
      const solved = this.userStats.problems.solved;
      const total = this.userStats.problems.total;
      return parseFloat(((solved / total) * 100).toFixed(2));
    },
    followText() {
      if (!this.isFollowing) return '关注';
      if (this.isFollowing && !this.isFollowers) return '已关注';
      if (this.isFollowing && this.isFollowers) return '互相关注';
      return '关注';
    }
  },
  async created() {
    await this.initProfileData();
  },

  methods: {
    // 显示编辑资料主模态框
    showEditModal() {
      this.editModalVisible = true;
    },
    
    // 从子模态框返回主编辑模态框
    backToEditModal() {
      this.usernameModalVisible = false;
      this.passwordModalVisible = false;
      this.avatarModalVisible = false;
      this.editModalVisible = true;
    },

    // 处理编辑菜单点击
    handleEditMenuClick({ key }) {
      this.editModalVisible = false;
      switch(key) {
        case 'avatar':
          this.avatarModalVisible = true;
          break;
        case 'username':
          this.usernameModalVisible = true;
          break;
        case 'password':
          this.passwordModalVisible = true;
          break;
      }
    },

    // 处理分页变化
    handlePaginationChange(page, type) {
      // 根据类型设置正确的分页current值
      if (type === 'solved' || type === 'attempting') {
        this.pagination.problems.current = page;
        this.loadProblemsData(type); // 直接使用传入的type加载数据
      } else if (type === 'published' || type === 'drafts' || type === 'liked') {
        this.pagination.blogs.current = page;
        this.loadBlogsData(type);
      } else if (type === 'following' || type === 'followers' || type === 'mutual') {
        this.pagination.friends.current = page;
        this.loadFriendsData(type);
      }
    },

    // 更新用户名
    async updateUsername() {
      const newUsername = this.usernameForm.newUsername.trim();
      if (!newUsername) {
        this.$message.warning('请输入新用户名');
        return;
      }

      try {
        const userStore = useUserStore();
        await userStore.updateUsername(newUsername);
        
        this.user.username = newUsername;
        this.$message.success('用户名更新成功');
        this.usernameModalVisible = false;
        this.editModalVisible = true;
      } catch (error) {
        console.error('更新用户名失败:', error);
        this.$message.error('用户名更新失败: ' + (error || '未知错误'));
      }
    },

    // 处理头像选择
    handleAvatarChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        this.avatarPreview = e.target.result;
      };
      reader.readAsDataURL(file);// 读取base64格式的数据，进行显示
      const readerbite = new FileReader();
      readerbite.onload = (e) => {
        this.avatarPreviewByte = e.target.result;
      };
      readerbite.readAsArrayBuffer(file);// 读取二进制格式的数据，进行上传
    },

    // 更新头像
    async updateAvatar() {
      if (!this.avatarPreviewByte) return;

      try {
        const userStore = useUserStore();
        const {path} = await userStore.updateAvatar(this.avatarPreviewByte);
        
        this.user.avatar = path;
        this.$message.success('头像更新成功');
        this.avatarModalVisible = false;
        this.editModalVisible = true;
        this.avatarPreview = null;
      } catch (error) {
        console.error('更新头像失败:', error);
        this.$message.error('头像更新失败: ' + (error || '未知错误'));
      }
    },

    // 修改密码
    async changePassword() {
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.$message.warning('两次输入的密码不一致');
        return;
      }

      try {
        const userStore = useUserStore();
        await userStore.changePassword(
          this.passwordForm.currentPassword,
          this.passwordForm.newPassword
        );
        
        this.$message.success('密码修改成功');
        this.passwordModalVisible = false;
        this.editModalVisible = true;
        this.passwordForm = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        };
        userStore.logout();
        this.$router.push("/");
      } catch (error) {
        console.error('修改密码失败:', error);
        this.$message.error('修改密码失败: ' + (error || '未知错误'));
      }
    },

    // 通过邮箱验证码修改密码
    async changePasswordByEmail() {
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.$message.warning('两次输入的密码不一致');
        return;
      }

      try {
        const userStore = useUserStore();
        await userStore.changePasswordByEmail(
          this.emailForm.verificationCode,
          this.passwordForm.newPassword
        );
        
        this.$message.success('密码修改成功');
        this.passwordModalVisible = false;
        this.editModalVisible = true;
        this.passwordForm = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        };
        this.emailForm.verificationCode = '';
        userStore.logout();
        this.$router.push("/");
      } catch (error) {
        console.error('修改密码失败:', error);
        this.$message.error('修改密码失败: ' + (error || '未知错误'));
      }
    },

    // 发送验证码
    async sendVerificationCode() {
      try {
        const userStore = useUserStore();
        const success = await userStore.sendVerificationCode(userStore.userStats.email);
        if (!success) {
          throw new Error('验证码发送失败');
        }
        this.$message.success('验证码已发送');
      } catch (error) {
        console.error('发送验证码失败:', error);
        this.$message.error('发送验证码失败: ' + (error || '未知错误'));
      }
    },

    // 切换验证方式
    toggleVerificationMethod() {
      this.useEmailVerification = !this.useEmailVerification;
      this.passwordForm.currentPassword = '';
      this.emailForm.verificationCode = '';
    },

    async loadProblems() {
      this.loading = true;
      this.error = null;
      try {
        const userStore = useUserStore();
        
        // 确保用户数据已加载
        if (!userStore.userStats || !userStore.userStats.email) {
          await userStore.fetchUserStats();
        }
        
        const userId = userStore.userStats.email;
        
        // 获取已通过题目(带分页参数)
        const solvedRes = await userStore.getSolvedProblems(
          userId, 
          this.pagination.problems.current,
          this.pagination.problems.pageSize
        );
        this.solvedProblems = (solvedRes?.problems || []).map(p => ({
          problemId: p?.problemId || p?.id || 0,
          problemTitle: p?.problemTitle || p?.title || '',
          difficultyLevel: p?.difficulty || 0,
          acceptanceRate: p?.acceptanceRate || 0
        }));
        this.pagination.problems.solvedTotal = solvedRes?.total || 0;
        
        // 获取尝试中题目(带分页参数)
        const attemptingRes = await userStore.getAttemptingProblems(
          userId,
          this.pagination.problems.current,
          this.pagination.problems.pageSize
        );
        this.attemptedProblems = (attemptingRes?.problems || []).map(p => ({
          problemId: p?.problemId || p?.id || 0,
          problemTitle: p?.problemTitle || p?.title || '',
          difficultyLevel: p?.difficulty || 0,
          acceptanceRate: p?.acceptanceRate || 0
        }));
        this.pagination.problems.attemptingTotal = attemptingRes?.total || 0;
      } catch (err) {
        console.error('加载题目失败:', err);
        this.error = '加载题目失败，请稍后重试';
        this.$message.error(this.error);
      } finally {
        this.loading = false;
      }
    },

    async initProfileData() {
      this.loading = true;
      try {
        const userStore = useUserStore();
        if (userStore.userStats.email === '') {
            await userStore.fetchUserStats();
        }
        const email = this.$route.query?.email || userStore.userStats.email;
        this.isSelf = email === userStore.userStats.email;
        // 1. 先获取基本信息和统计数据
        const { stats , prodata } = await userStore.fetchUserStats(email,"");
        this.user = {
          username: stats.name || '',
          email: stats.email || '',
          avatar: stats.avatar || ''
        };
        this.userStats = {
            problems:{
                solved: stats.solvedCount,
                total: stats.totalProblems
            },
            blogs:{
                likes: prodata.blog_likes_number
            },
            friends: {
                following: prodata.following,
                followers:prodata.followers
            }
        }
        this.pagination =  { 
            problems: {
              current: 1,
              pageSize: 10,
              solvedTotal: prodata.solved,
              attemptingTotal: prodata.attempting
            },
            blogs: {
              current: 1,
              pageSize: 10,
              publishedTotal: prodata.published,
              draftsTotal: prodata.drafts
            },
            friends: {
              current: 1,
              pageSize: 10,
              followingTotal: prodata.following,
              followersTotal: prodata.followers,
              mutualTotal: prodata.mutual,
            }
        }

        // 2. 根据路由参数加载详细数据
        const tab = this.$route.query.tab || 'problems';
        this.activeContentKey = [tab];
        
        if (tab === 'problems') {
          await this.loadProblemsData('solved');
        } else if (tab === 'blogs') {
          await this.loadBlogsData('published');
        } else if (tab === 'friends') {
          await this.loadFriendsData('following');
        }
      } catch (error) {
        console.error('初始化个人资料失败:', error);
        this.$message.error('加载个人资料失败');
      } finally {
        this.loading = false;
      }
    },
    onBlogClick(blog) {
      this.$router.push(`/blogs/${blog.id}`)
    },
    

    handleTabChange(activeKey, tabType) {
      // 重置当前页为第一页
      if (tabType === 'problems') {
        this.pagination.problems.current = 1;
        if (activeKey === '1') {
          this.loadProblemsData('solved');
        } else if (activeKey === '2') {
          this.loadProblemsData('attempting');
        }
      } else if (tabType === 'blogs') {
        this.pagination.blogs.current = 1;
        if (activeKey === '1') {
          this.loadBlogsData('published');
        } else if (activeKey === '2') {
          this.loadBlogsData('drafts');
        } else if (activeKey === '3') {
          this.loadBlogsData('liked');
        }
      } else if (tabType === 'friends') {
        this.pagination.friends.current = 1;
        if (activeKey === '1') {
          this.loadFriendsData('following');
        } else if (activeKey === '2') {
          this.loadFriendsData('followers');
        } else if (activeKey === '3') {
          this.loadFriendsData('mutual');
        }
      }
    },

    async loadProblemsData(type) {
      this.loading = true;
      try {
        const userProblem = useProblemStore();
        const userId = this.user.email;
        
        if (type === 'solved') {
          const solvedRes = await userProblem.getSolvedProblems(
            userId,
            this.pagination.problems.current,
            this.pagination.problems.pageSize
          );
          this.solvedProblems = (solvedRes?.problems || []).map(p => ({
            problemId: p?.problemId || p?.id || 0,
            problemTitle: p?.problemTitle || p?.title || '',
            difficultyLevel: p?.difficulty || 0,
            acceptanceRate: p?.acceptanceRate || 0,
          }));
        //   this.pagination.problems.solvedTotal = solvedRes?.total || 0;
        } else if (type === 'attempting') {
          const attemptingRes = await userProblem.getAttemptingProblems(
            userId,
            this.pagination.problems.current,
            this.pagination.problems.pageSize
          );
          this.attemptedProblems = (attemptingRes?.problems || []).map(p => ({
            problemId: p?.problemId || p?.id || 0,
            problemTitle: p?.problemTitle || p?.title || '',
            difficultyLevel: p?.difficulty || 0,
            acceptanceRate: p?.acceptanceRate || 0
          }));
        //   this.pagination.problems.attemptingTotal = attemptingRes?.total || 0;
        }
      } catch (error) {
        console.error('加载题目失败:', error);
        this.$message.error('加载题目失败');
      } finally {
        this.loading = false;
      }
    },
    handleDeleteBlog() {
      // 删除博客后，重新加载博客数据
      this.loadBlogsData('published');
      this.loadBlogsData('drafts');
      this.loadBlogsData('liked');
    },

    async loadBlogsData(type) {
      // TODO: 实现博客数据加载
      this.loading = true;
      this.error = null;
      try {
        const useBlog = useBlogStore();
        const userId = this.user.email;
        if (type === 'published') {
          const publishedRes = await useBlog.getPublishedBlogs(
            userId,
            this.pagination.blogs.current,
            this.pagination.blogs.pageSize
          );
          this.publishedBlogs = publishedRes?.blogs || [];
          this.pagination.blogs.publishedTotal = publishedRes?.total || 0;
        } else if (type === 'drafts') {
          const draftRes = await useBlog.getDraftBlogs(
            userId,
            this.pagination.blogs.current,
            this.pagination.blogs.pageSize
          );
          this.draftBlogs = draftRes?.blogs || [];
          this.pagination.blogs.draftsTotal = draftRes?.total || 0;
        } else if (type === 'liked') {
            const likedRes = await useBlog.getLikedBlogs(
            this.user.email,
            this.pagination.blogs.current,
            this.pagination.blogs.pageSize
          );
          this.likedBlogs = likedRes?.blogs || [];
          this.pagination.blogs.likedTotal = likedRes?.total || 0;
        }
      } catch (error) {
        console.error('加载博客失败:', error);
        this.$message.error('加载博客失败');
      } finally {
        this.loading = false;
      }
    },

    async loadFriendsData(type) {
      this.loading = true;
      try {
        const userStore = useUserStore();
        const email = this.$route.query?.email || userStore.userStats.email;
        this.isSelf = email === userStore.userStats.email;
        
        if (type === 'following') {
          const result = await userStore.fetchFollowing(email, 1, 50); // 获取前50个
          if (result.success) {
            this.following = result.users;
          }
        } else if (type === 'followers') {
          const result = await userStore.fetchFollowers(email, 1, 50);
          if (result.success) {
            this.followers = result.users;
          }
        } else if (type === 'mutual') {
          const result = await userStore.fetchMutualFollowers(1, 50);
          if (result.success) {
            this.mutualFriends = result.users;
          }
        }
      } catch (error) {
        console.error('加载好友失败:', error);
        this.$message.error('加载好友失败');
      } finally {
        this.loading = false;
      }
    },

    
    handleMainMenuSelect({ key }) {
        this.activeContentKey = [key];
        if (key === 'problems') {
        this.loadProblemsData('solved');
        } else if (key === 'blogs') {
        this.loadBlogsData('published');
        } else if (key === 'friends') {
        this.loadFriendsData('following');
        }
    },
    async fetchFollowStatus() {
        this.followLoading = true
        try {
            const res = await getFollowStatus(this.user.email)
            this.following = res.following
            this.followers = res.followers
        } catch (error) {
            message.error(error)
        } finally {
            this.followLoading = false
        }
    },
    async onFollowClick() {
        if (!this.following) {
            // 关注
            try {
                const res = await follow(this.user.email)
                message.success(res.message)
                this.fetchFollowStatus()
            } catch (error) {
                message.error(error)    
            }

        } else {
            // 已关注/互相关注，弹窗确认
            Modal.confirm({
            title: '取消关注',
            content: '确定要取消关注该用户吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const res = await unfollow(this.user.email)
                    message.success(res.message)
                    this.fetchFollowStatus()
                } catch (error) {
                    message.error(error)
                }
            }
            })
        }
    }
  },

  watch: {
    '$route.query.tab'(newTab) {
      if (newTab) {
        this.activeContentKey = [newTab];
        if (newTab === 'problems' && this.solvedProblems.length === 0) {
            this.loadProblems("solved");
        }else if (newTab === 'blogs' && this.publishedBlogs.length === 0){
            this.loadBlogsData("published");
        }else if (newTab === 'friends' && this.following.length === 0){
            this.loadBlogsData("following");
        }
      }
    },
    '$route.query.email'(newEmail, oldEmail) {
    if (newEmail !== oldEmail) {
      this.initProfileData();
    }
  }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  gap: 40px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  min-width: 160px;
}

.username {
  font-size: 18px;
  font-weight: 500;
}

.user-email {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.edit-btn {
  width: 100%;
}

.stats-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  flex-grow: 1;
}

.stats-row {
  display: flex;
  gap: 40px;
  justify-content: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-text {
  font-size: 16px;
  font-weight: 500;
}

.profile-content {
  margin-top: 24px;
}

.content-menu {
  margin-bottom: 16px;
  background: #fff;
  padding: 0 16px;
  border-radius: 8px;
}

.content-display {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  min-height: 400px;
}

.avatar-edit-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.avatar-wrapper {
  margin-bottom: 32px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 32px;
}

.confirm-btn {
  min-width: 120px;
}

.cancel-btn {
  min-width: 120px;
  background: #f5f5f5;
}

@media (max-width: 992px) {
  .profile-content {
    grid-template-columns: 1fr;
  }
}
</style>;
